package com.dm.library.utils;

import android.content.Context;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.dm.library.R;

public class ToastUtil {

    private static ToastUtil util;
    private Toast toast;
    private CharSequence oldMsg;
    private long time;

    private ToastUtil() {
    }

    public synchronized static ToastUtil getInstant() {
        if (util == null) {
            util = new ToastUtil();
        }
        return util;
    }

    /**
     * 显示Toast
     *
     * @param context
     * @param text
     */
    public void show(Context context, String text) {
        if (TextUtils.isEmpty(text) || context == null) {
            return;
        }
        if (toast == null) {
            toast = new Toast(context);
        }
        if (!text.equals(oldMsg)) { // 当显示的内容不一样时，即断定为不是同一个Toast
            showInfo(context, text, Toast.LENGTH_SHORT);
            time = System.currentTimeMillis();
        } else {
            // 显示内容一样时，只有间隔时间大于2秒时才显示
            if (System.currentTimeMillis() - time > 2000) {
                showInfo(context, text, Toast.LENGTH_SHORT);
                time = System.currentTimeMillis();
            }
        }
        oldMsg = text;
    }

    /**
     * 显示Toast
     *
     * @param context
     * @param text
     * @param duration
     */
    public void show(Context context, String text, int duration) {
        if (TextUtils.isEmpty(text)) {
            return;
        }
        if (toast == null) {
            toast = new Toast(context);
        }

        if (!text.equals(oldMsg)) {
            showInfo(context, text, duration);
            time = System.currentTimeMillis();
        } else {
            if (System.currentTimeMillis() - time > 2000) {
                showInfo(context, text, duration);
                time = System.currentTimeMillis();
            }
        }
    }

    private void showInfo(Context context, String text, int duration) {
        View view = View.inflate(context, R.layout.toast_view, null);
        TextView textView = (TextView) view.findViewById(R.id.toast_text);
        textView.setText(text);
        toast.setGravity(Gravity.CENTER, 0, 80);
        toast.setDuration(duration);
        toast.setView(view);
        toast.show();
    }
}
